package com.SFA.OrderManagement;


import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Calendar;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.FrameWork.Common.CommonFunction;
import com.FrameWork.Common.MyApplication;
import com.FrameWork.Entity.OrderEntity;
import com.FrameWork.Entity.PaymentEntity;
import com.FrameWork.Utils.DateTimeUtils;
import com.FrameWork.Utils.Utils;
import com.SFA.R;

public class ConfirmOrderFragment extends Fragment implements OnClickListener {

	private ImageView btnAdd;
	private OrderEntity entity= null;
	private TextView txtTotalAmount,txtTotalOrgAmount,txthistoryAmount,txtOrderDate;
	private EditText txtNote;
	private Button txtDiscountAmount;
	private EditText txtContactMan,txtContact,txtAddress;
	private ListView historyPayment;
	private DatePicker deliveryDate;
	private HistoryPaymentAdapter historyPaymentAdapter;
	private RadioButton rdoSelf,rdoDelivery,rdoExpress;
	public  int payType=0;
	float history_money=0;
	private OrderManager manager = new OrderManager();

	

	private void setData()
	{
		if(entity.REQ_DELIVERY_DATE==null){
			entity.REQ_DELIVERY_DATE=DateTimeUtils.GetCurrentTime();
		}
		historyPaymentAdapter=new HistoryPaymentAdapter(entity.paymentlist, this.getActivity());
		historyPayment.setAdapter(historyPaymentAdapter);
		ComputeHeight();
		txtOrderDate.setText(DateTimeUtils.getSelects12Date(entity.ORDER_DATE));
		try
		{
			txtContactMan.setText(entity.CONTACT_MAN);
			txtContact.setText(entity.CONTACT_LINK);
			txtAddress.setText(entity.DELIVERY_ADDRESS);
			txtNote.setText(entity.ADDITIONAL_INFO);
			RefreshPayment();


			if(!TextUtils.isEmpty(entity.REQ_DELIVERY_DATE)){
				long millis = DateTimeUtils.getMillisFromFromLongDate(entity.REQ_DELIVERY_DATE);
				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(millis);

				deliveryDate.updateDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

			}
			if(entity.DELIVERY_TYPE ==3)
			{
				rdoExpress.setChecked(true);
			}
			else if(entity.DELIVERY_TYPE ==2)
			{
				rdoDelivery.setChecked(true);
			}
			else
			{
				rdoSelf.setChecked(true);
			}
		}
		catch(Exception err){
			err.printStackTrace();
		}
	}


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.confirm_order, container, false);
		btnAdd = (ImageView)v.findViewById(R.id.btnAdd);
		btnAdd.setOnClickListener(this); 

		historyPayment=(ListView) v.findViewById(R.id.lv_payment);
		txtOrderDate= (TextView)v.findViewById(R.id.txtOrderDate);
		txtTotalAmount = (TextView)v.findViewById(R.id.txtTotalAmount);
		txtTotalOrgAmount = (TextView)v.findViewById(R.id.txtTotalOrgAmount);
		txthistoryAmount=(TextView) v.findViewById(R.id.txthistoryAmount);
		txtDiscountAmount =  (Button)v.findViewById(R.id.txtDiscountAmount);
		//弹出式控制数字输入
		txtDiscountAmount.setOnClickListener(this);
		txtContactMan=  (EditText)v.findViewById(R.id.txtContactMan);
		
		txtContactMan.addTextChangedListener(watcher1);
		txtContact=  (EditText)v.findViewById(R.id.txtContact);
		txtContact.addTextChangedListener(watcher2);
		txtAddress=  (EditText)v.findViewById(R.id.txtAddress);
		txtAddress.addTextChangedListener(watcher3);
		txtNote=  (EditText)v.findViewById(R.id.txtNote);
		txtNote.addTextChangedListener(watcher4);
		deliveryDate= (DatePicker)v.findViewById(R.id.calendarDeliveryDate);
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		minYear=calendar.get(Calendar.YEAR);
		minMonth=calendar.get(Calendar.MONTH);
		minDay=calendar.get(Calendar.DAY_OF_MONTH);
		deliveryDate.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),  calendar.get(Calendar.DAY_OF_MONTH), onDateChangedListener);
		rdoSelf= (RadioButton)v.findViewById(R.id.rdoSelf);
		rdoDelivery= (RadioButton)v.findViewById(R.id.rdoDelivery);
		rdoExpress= (RadioButton)v.findViewById(R.id.rdoExpress);
		return v;

	}
	
	TextWatcher watcher1 = new TextWatcher()
	{
		
		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			entity.CONTACT_MAN =arg0.toString();
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			entity.CONTACT_MAN =s.toString();
			
		}
		
	};
	
	
	TextWatcher watcher3 = new TextWatcher()
	{
		
		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			entity.DELIVERY_ADDRESS =arg0.toString();
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			entity.DELIVERY_ADDRESS =s.toString();
			
		}
		
	};
	
	TextWatcher watcher4 = new TextWatcher()
	{
		
		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			entity.ADDITIONAL_INFO =arg0.toString();
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			entity.ADDITIONAL_INFO =s.toString();
			
		}
		
	};
	
	TextWatcher watcher2 = new TextWatcher()
	{
		
		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			entity.CONTACT_LINK =arg0.toString();
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			entity.CONTACT_LINK =s.toString();
			
		}
		
	};
	
	

	private int minYear,minMonth,minDay;

	private OnDateChangedListener onDateChangedListener  = new OnDateChangedListener()
	{

		@Override
		public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
		{
			if (year < minYear ||
					(monthOfYear < minMonth && year == minYear)
					||(dayOfMonth < minDay && year == minYear && monthOfYear == minMonth))
					view.updateDate(minYear, minMonth, minDay);
			else
			{
				long delivery =(long) (deliveryDate.getYear() *10000 + (deliveryDate.getMonth()+1) *100 + deliveryDate.getDayOfMonth())*1000000;
				entity.REQ_DELIVERY_DATE=delivery+ "";
			}

			/*	if (year > maxYear)
				view.updateDate(maxYear, maxMonth, maxDay);

			if (monthOfYear > maxMonth && year == maxYear)
				view.updateDate(maxYear, maxMonth, maxDay);

			if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
				view.updateDate(maxYear, maxMonth, maxDay);*/
		}}; 

		public void LoadData(OrderEntity entity)
		{
			this.entity = entity;
			setData();
		}

		@Override
		public void onClick(View v) {
			if(v == btnAdd) //添加付款记录
			{
				toAddMethod();

			}
			else if(v== txtDiscountAmount)
			{

				LayoutInflater factory = LayoutInflater.from(getActivity());//提示框
				final View view = factory.inflate(R.layout.input_layout, null);//这里必须是final的
				final EditText edit=(EditText)view.findViewById(R.id.txtAmount);//获得输入框对象
				edit.setHint("再次输入优惠金额");//输入框默认值
				edit.setText(entity.DISC_AMOUNT + "");
				new AlertDialog.Builder(getActivity())
				.setTitle("在下面输入你的优惠金额")//提示框标题
				.setView(view)
				.setPositiveButton("确定",//提示框的两个按钮
						new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						dialog.dismiss();
						//事件处理
						try {
							if(!TextUtils.isEmpty(edit.getText())){
								float double_DisCountAmount=Float.parseFloat(edit.getText().toString());
								float unpayment = entity.TOTAL_AMOUNT - history_money;
								BigDecimal a = new BigDecimal(unpayment); 
								a= a.setScale(2, BigDecimal.ROUND_HALF_UP);
								BigDecimal b = new BigDecimal(double_DisCountAmount); 
								b=b.setScale(2, BigDecimal.ROUND_HALF_UP);
								if(a.floatValue()-b.floatValue()<0)
								{
									CommonFunction.ShowDialog(getActivity(), "优惠金额不能大于" + String.valueOf(Utils.convert(unpayment)) +"元");
									return;
								}
								entity.DISC_AMOUNT = double_DisCountAmount;
								RefreshPayment();
							}

						} catch (Exception e) {
							CommonFunction.ShowDialog(getActivity(), "优惠金额输入有误");

						}

					}
				}).setNegativeButton("取消", null).create().show();

			}

		}


		public void toSaveMethod() {
			//保存订单
			if(TextUtils.isEmpty(entity.STATUS))
				entity.STATUS="0";
			if(TextUtils.isEmpty(txtContactMan.getText().toString()))
			{
				CommonFunction.ShowDialog(getActivity(), "请输入客户姓名，谢谢!");
				return;
			}
			if(TextUtils.isEmpty(txtContact.getText().toString()))
			{
				CommonFunction.ShowDialog(getActivity(), "联系方式不能为空!");
				return;
			}

			entity.ADDITIONAL_INFO = ConfirmOrderFragment.this.txtNote.getText().toString();
			entity.CONTACT_LINK = ConfirmOrderFragment.this.txtContact.getText().toString();
			entity.CONTACT_MAN = ConfirmOrderFragment.this.txtContactMan.getText().toString();
			entity.DELIVERY_ADDRESS = ConfirmOrderFragment.this.txtAddress.getText().toString();
			entity.DELIVERY_TYPE = rdoSelf.isChecked() ? 1 : rdoDelivery.isChecked()? 2:3;
			entity.CONFIRMED_DATE=DateTimeUtils.GetCurrentTime();
			long delivery =(long) (deliveryDate.getYear() *10000 + (deliveryDate.getMonth()+1) *100 + deliveryDate.getDayOfMonth())*1000000;
			entity.REQ_DELIVERY_DATE=delivery+ "";
			
			if(delivery<Long.parseLong(DateTimeUtils.GetCurrentTime())){
				CommonFunction.ShowDialog(ConfirmOrderFragment.this.getActivity(), "提货日期不能小于当前日期");
			}else if(Double.parseDouble(txtTotalAmount.getText().toString().trim())<0){
				CommonFunction.ShowDialog(ConfirmOrderFragment.this.getActivity(), "优惠金额不能大于应付金额");
			}else{
				boolean updateDB = manager.updateCancelDB(entity.ORDER_NO,false);
				boolean updatePayment=true;
				//manager.updatePaymentActive(GlobalInfo.GetInstance(getActivity()).getUserID(),false);
				if(updateDB && updatePayment && manager.Save(getActivity(), entity,false)){
					//订单提交成功,是否立刻进行打印呢
					
					this.getActivity().finish();

				}else{
					CommonFunction.ShowDialog(getActivity(), "订单保存出现异常，请重新尝试");
				}
			}
		}

		private void toAddMethod() {
			LayoutInflater inflater=LayoutInflater.from(this.getActivity());
			final View view=inflater.inflate(R.layout.pay_record, null);
			final TextView payDate=(TextView) view.findViewById(R.id.pay_date);
			RadioButton rbMoney=(RadioButton) view.findViewById(R.id.rb_money);
			final RadioGroup paymentType=(RadioGroup) view.findViewById(R.id.paymentType);
			rbMoney.setChecked(true);
			final EditText payMoney=(EditText) view.findViewById(R.id.payMoney);
			DecimalFormat fnum = new DecimalFormat("##0.00"); 
			String dd=fnum.format(entity.TOTAL_AMOUNT - history_money-entity.DISC_AMOUNT); 

			payMoney.setText(dd);
			payMoney.setHint("请输入付款金额");
			final String date=DateTimeUtils.GetCurrentTime();
			payDate.setText(date.substring(0, 4)+"年"+date.substring(4, 6)+"月"+date.substring(6, 8)+"日  "+date.substring(8, 10)+"时"+date.substring(10, 12)+"分");

			new AlertDialog.Builder(this.getActivity()).setTitle("付款记录")
			.setView(view)
			.setNegativeButton(R.string.CANCEL, null)
			.setPositiveButton(R.string.ENSURE, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					String str_payMoney=payMoney.getText().toString();
					float payMoney=0;
					PaymentEntity payments=new PaymentEntity();
					payType = paymentType.getCheckedRadioButtonId() ==R.id.rb_money ? 0:1;
					payments.PAYMENT_TYPE=payType;
					payments.ORDER_ID=entity.ID;
					if(TextUtils.isEmpty(str_payMoney)){
						CommonFunction.ShowDialog(getActivity(), "请输入付款金额");
						return;
					}
					try {
						payMoney=Float.parseFloat(str_payMoney);
						if(payMoney<=0){
							CommonFunction.ShowDialog(getActivity(), "付款金额输入有误，请检查");
							return;
						}
					
						BigDecimal a = new BigDecimal(payMoney); 
						a= a.setScale(2, BigDecimal.ROUND_HALF_UP);
						BigDecimal b = new BigDecimal(entity.TOTAL_AMOUNT - history_money-entity.DISC_AMOUNT); 
						b=b.setScale(2, BigDecimal.ROUND_HALF_UP);
						if(a.floatValue()>b.floatValue())
						{
							CommonFunction.ShowDialog(getActivity(), "付款金额应不大于于应付金额");

							return;
						}

						payments.PAYMENT_AMOUNT=str_payMoney;
						payments.PAYMENT_TYPE=payType;
						payments.ORDER_ID=entity.ID;
						payments.CUSTOMER_ID=entity.CUSTOMER_ID;
						payments.PAYMENT_DATE=DateTimeUtils.GetCurrentTime();
						entity.paymentlist.add(payments);

						historyPaymentAdapter.notifyDataSetChanged();
						ComputeHeight();
						RefreshPayment();

					} catch (Exception e) {
						CommonFunction.ShowDialog(getActivity(), "请检查金额是否正确");
					}

				}
			}).show();
		}

		private void ComputeHeight()
		{
			//计算高度
			int totalHeight = 0;
			for (int i = 0; i < historyPaymentAdapter.getCount(); i++) {
				View listItem = historyPaymentAdapter.getView(i, null, historyPayment);
				listItem.measure(0, 0);
				totalHeight += listItem.getMeasuredHeight();

			}

			ViewGroup.LayoutParams params = historyPayment
					.getLayoutParams();
			params.height = totalHeight
					+ (historyPayment.getDividerHeight() * (historyPaymentAdapter
							.getCount() - 1));
			historyPayment.setLayoutParams(params);
		}


		private void RefreshPayment()
		{
			history_money=0;
			if(entity.paymentlist != null)
			{
				for (int i = 0; i < entity.paymentlist.size(); i++) {
					history_money+=Float.parseFloat(entity.paymentlist.get(i).PAYMENT_AMOUNT);
				}
			}
			entity.EXTENDED_AMOUNT = (float) history_money;
			txthistoryAmount.setText(String.valueOf(history_money));
			float totalamount = entity.TOTAL_AMOUNT - history_money-entity.DISC_AMOUNT;
			if(totalamount<=0){
				btnAdd.setVisibility(View.GONE);
			}else{
				btnAdd.setVisibility(View.VISIBLE);
			}
			DecimalFormat fnum = new DecimalFormat("##0.00"); 
			String dd=fnum.format(entity.TOTAL_AMOUNT); 
			txtTotalOrgAmount.setText(dd);
			dd=fnum.format(entity.DISC_AMOUNT); 
			txtDiscountAmount.setText(dd);
			dd=fnum.format(totalamount); 
			txtTotalAmount.setText(dd);
		}

}
